package org.dromara.xhlj.system.service.Impl;

import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import org.apache.commons.io.IOUtils;
import org.dromara.common.core.service.DictService;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.dromara.xhlj.domain.vo.XhljActivityVo;
import org.dromara.xhlj.system.font.FontLoader;
import org.dromara.xhlj.system.service.IXhljActivityService;
import org.dromara.xhlj.mapper.XhljActivityMapper;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.stream.Collectors;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

@Service
public class XhljActivityServiceImpl implements IXhljActivityService {
    @Autowired
    private ISysOssService ossService;
    @Autowired
    private XhljActivityMapper baseMapper;
    @Autowired
    private DictService dictService;

    @Override
    public SysOssVo poster(Integer activityId) throws Exception {
        XhljActivityVo activityVo = baseMapper.selectVoById(activityId);
        //活动标题
        String activityTitle = activityVo.getActivityTitle();
        //活动内容
        String activityContent = activityVo.getActivityContent();
        String activityContentText = Jsoup.parse(activityContent).text();
        String[] contents = activityContentText.split(" ");
        String content = contents[1];
        //活动开始时间
        Date activityStartDate = activityVo.getActivityStartTime();
        String time = formatDate(activityStartDate);
        // 互动福利
        String reward = "活动中积极互动，即有机会获得大会限定惊喜大礼包";
        //活动形式
        String type = dictService.getDictLabel("activity_type", activityVo.getActivityType());
        String activityTags = dictService.getDictLabel("activity_tags", activityVo.getActivityType());
        //活动类型
        String tags = Arrays.stream(activityTags.split(","))
            .map(s -> "※" + s)
            .collect(Collectors.joining(" ▎"));
        String bgImageUrl = "https://imutoj.cn/ruoyi/2024/07/25/4d41d4e0a93c44f9a3057bec856547e1.jpg";                  //背景图（测试url形式）
        String qrCodeUrl = "https://imutoj.cn/ruoyi/2024/07/25/9ab2f6a79fc84ba4844383e976f24006.png";                   //二维码

        //合成器和背景图（整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
        ImageCombiner combiner = new ImageCombiner(bgImageUrl, 380, 674, ZoomMode.WidthHeight, OutputFormat.PNG);
        combiner.setCanvasRoundCorner(100); //设置整图圆角（输出格式必须为PNG）

        // 加载思源字体
        String fontUrl = "https://imutoj.cn/font-style/SourceHanSansSC-Bold.otf";
        Font boldFont40 = FontLoader.getInstance().getFontFromURL(fontUrl, 40, Font.BOLD);
        Font boldFont15 = FontLoader.getInstance().getFontFromURL(fontUrl, 15, Font.BOLD);
        Font boldFont13 = FontLoader.getInstance().getFontFromURL(fontUrl, 13, Font.PLAIN);
        Font boldFont16 = FontLoader.getInstance().getFontFromURL(fontUrl, 16, Font.PLAIN);

        //标题
        combiner.addTextElement(activityTitle, boldFont40, 67, 41)
            .setAutoBreakLine(380, 2, 42)
            .setColor(Color.white)
            .setCenter(true);

        //活动内容
        combiner.addTextElement("活动主题：", boldFont15, 50, 357)
            .setAutoBreakLine(80, 1, 25)
            .setColor(new Color(117, 249, 253, 179));
        combiner.addTextElement(content, boldFont13, 123, 361)
            .setAutoBreakLine(185, 3, 19)
            .setColor(Color.white);

        //内容
        combiner.addTextElement("活动类别：", boldFont15, 50, 416)
            .setAutoBreakLine(80, 1, 25)
            .setColor(new Color(117, 249, 253, 179));
        combiner.addTextElement(tags, boldFont13, 123, 420)
            .setAutoBreakLine(187, 3, 19)
            .setColor(Color.white);

        combiner.addTextElement("活动时间：", boldFont15, 50, 458)
            .setAutoBreakLine(80, 1, 25)
            .setColor(new Color(117, 249, 253, 179));
        combiner.addTextElement(time, boldFont13, 123, 462)
            .setAutoBreakLine(185, 1, 19)
            .setColor(Color.white);

        combiner.addTextElement("活动形式：", boldFont15, 50, 494)
            .setAutoBreakLine(80, 1, 25)
            .setColor(new Color(117, 249, 253, 179));
        combiner.addTextElement(type, boldFont13, 123, 498)
            .setAutoBreakLine(185, 1, 19)
            .setColor(Color.white);

        combiner.addTextElement("互动福利：", boldFont15, 50, 530)
            .setAutoBreakLine(80, 1, 25)
            .setColor(new Color(117, 249, 253, 179));
        combiner.addTextElement(reward, boldFont13, 123, 534)
            .setAutoBreakLine(187, 2, 19)
            .setColor(Color.white);

        //二维码
        combiner.addImageElement(qrCodeUrl, 50, 575, 44, 44, ZoomMode.WidthHeight);
        combiner.addTextElement("<<<", boldFont13, 113, 578)
            .setColor(Color.white);
        combiner.addTextElement("扫码报名参加", boldFont13, 113, 597)
            .setColor(Color.white);

        combiner.addTextElement("名额有限◎赶紧报名", boldFont16, 119, 308)
            .setColor(Color.black);

        //执行图片合并
        combiner.combine();

        //可以获取流（并上传oss等）
        InputStream is = combiner.getCombinedImageStream();
        byte[] data = IOUtils.toByteArray(is);
        String contentType = "image/png";
        String suffix = ".png";
        SysOssVo upload = ossService.upload(data, suffix, contentType);
        return upload;
    }

    private String formatDate(Date date) {
        LocalDateTime dateTime = date.toInstant()
            .atZone(ZoneId.systemDefault())
            .toLocalDateTime();

        DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("M月d日", Locale.CHINA);
        DateTimeFormatter weekFormatter = DateTimeFormatter.ofPattern("EEEE", Locale.CHINA);

        String monthDay = dateTime.format(dayFormatter);
        String dayOfWeek = dateTime.format(weekFormatter);
        String period = dateTime.getHour() < 12 ? "上午" : "下午";
        int hour = dateTime.getHour() % 12 == 0 ? 12 : dateTime.getHour() % 12;
        return String.format("%s（%s）%s%d点", monthDay, dayOfWeek, period, hour);
    }
}
